package com.yuexunit.finance.system.action.v1;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;

import com.google.inject.Singleton;
import com.yuexunit.fs.domain.FileEntry;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;
import com.yuexunit.web.annotation.ActionServlet;

import sun.misc.BASE64Decoder;

/**
 *@version 创建时间：2016年12月13日 下午6:32:09
 *@author wenwenlong
 *类说明
 */

@ActionServlet({"/api/[^/]+/newUploadFile.json"})
@Singleton
public class NewUploadFileAction extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private static final Pattern P_CHARSET = Pattern.compile("(?i)(<[^>]+charset=)([^\\s\"'>]+)");

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		InputStream fileUploaded = null;
		String result = "";

		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");

			String imgData = request.getParameter("imgData");
			String imgName = request.getParameter("imgName");

			FileEntry fileEntry = new FileEntry(imgName);
			File file = new File(fileEntry.getServerAbsolutePath());
			File parentDir = file.getParentFile();
			if ((parentDir != null) && (!(parentDir.exists()))) {
				parentDir.mkdirs();
			}
			FileOutputStream output = new FileOutputStream(file);
			byte[] buffer = new BASE64Decoder().decodeBuffer(imgData);
			fileUploaded = new ByteArrayInputStream(buffer); 
			byte[] buf = new byte[10240];
			int len = 0;
			while ((len = fileUploaded.read(buf)) != -1) {
				output.write(buf, 0, len);
			}
			fileUploaded.close();
			output.close();

			fileEntry.setFileSize(Long.valueOf(file.length()));

			insertFileEntry(fileEntry);

			resetEncode(fileEntry);
			result = getResult(fileEntry);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "{\"act\":\"uploadFile\",\"version\":\"v1.0\",\"flag\":\"FAILURE\",\"msg\":\"上传文件失败\",\"data\":[]}";
		} finally {
			try {
				if (fileUploaded != null)
					fileUploaded.close();
			}
			catch (Exception localException3)
			{
			}
			response.getWriter().write(result);
		}
	}

	private void resetEncode(FileEntry fileEntry) {
		if (!(fileEntry.isHtmlFile()))
			return;
		try
		{
			File resumeFile = new File(fileEntry.getServerAbsolutePath());
			byte[] buffer = new byte[4096];
			FileInputStream fis = new FileInputStream(resumeFile);
			ByteArrayOutputStream bao = new ByteArrayOutputStream();

			int len = 0;
			while ((len = fis.read(buffer)) != -1) {
				bao.write(buffer, 0, len);
			}
			bao.flush();
			byte[] htmlBytes = bao.toByteArray();

			fis.close();
			bao.close();

			String html = new String(htmlBytes, "utf-8");

			Matcher m = P_CHARSET.matcher(html);
			if (m.find()) {
				String charset = m.group(2);
				if (!("utf-8".equalsIgnoreCase(charset))) {
					html = new String(htmlBytes, charset);
					html = html.replaceFirst(charset, "utf-8");

					OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(resumeFile, false), "utf-8");
					writer.write(html);
					writer.flush();
					writer.close();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Transactional
	public void insertFileEntry(FileEntry fileEntry) {
		fileEntry.setCreateTime(DateUtil.now());
		PersistUtil.insert(fileEntry);
	}

	private String getResult(FileEntry fileEntry) {
		StringBuilder data = new StringBuilder(512);
		data.append("{\"fileName\":\"").append(StringEscapeUtils.escapeJavaScript(fileEntry.getFileName()))
		.append("\",\"fileUuid\":\"")
		.append(fileEntry.getFileUuid())
		.append("\",\"fileSize\":\"")
		.append(fileEntry.getFileSize())
		.append("\"}");

		String json = "{\"act\":\"uploadFile\",\"version\":\"v1.0\",\"flag\":\"SUCCESS\",\"msg\":\"上传文件成功\",\"data\":[${data}]}".replace("${data}", data.toString());

		return json;
	}
}
